package com.hengxinguotong.zhihuichengjian.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.NewsListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.News;
import com.hengxinguotong.zhihuichengjian.bean.NewsInfo;
import com.hengxinguotong.zhihuichengjian.database.NewsDAO;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hengxinguotong.zhihuichengjian.widget.view.CustomPatient;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/25.
 */

public class ArticleListActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.tv_back)
    HXTextView tvBack;
    @BindView(R.id.tv_title)
    HXTextView tvTitle;
    @BindView(R.id.article_list)
    PullToRefreshListView articleList;

    private ArticleListActivity mActivity;
    private NewsListAdapter adapter;
    private int pageIndex = 1;
    private int type = 6;//资讯类型(2:广告;3:城乡建设;4:海绵城市;5:综合管廊;6:BIM)
    private List<News> newsList;
    private NewsDAO service;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_list);
        ButterKnife.bind(this);
        mActivity = this;
        tvTitle.setText("文章收藏");
        articleList.setMode(PullToRefreshBase.Mode.BOTH);
        initData();
//        getNewsList("加载中…");
        setListener();
    }

    @OnClick({R.id.tv_back})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_back:
                finish();
                break;
        }
    }

    private void initData(){
        service = new NewsDAO(this);
        newsList = service.selectAll();
        if(null == newsList || newsList.size() == 0){
            showEmptyView(articleList);
        }else{
            processNews(newsList);
        }
    }

    private void setListener(){
        articleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mActivity, WebViewActivity.class);
                intent.putExtra("news", newsList.get(position -1));
                intent.putExtra("title", "新闻资讯");
                mActivity.startActivity(intent);
            }
        });

        articleList.getRefreshableView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showDialog(newsList.get(position - 1));
                return true;//true 长按之后无短按事件；false 长按之后又短按事件
            }
        });

        articleList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getNewsList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getNewsList(null);
            }
        });
    }

    /*
     *获取资讯信息
     */
    private void getNewsList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        params.addBodyParameter("pageNum", pageIndex + "");
        Utils.requestData(alert, mActivity, "/news/queryInformationList/" + SPUtil.getString(mActivity,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(articleList.isRefreshing()){
                    articleList.onRefreshComplete();
                }
                if(!Utils.isEmpty(json)){
                    SPUtil.put(mActivity, "newsList", json);
                    Gson gson = new Gson();
                    NewsInfo newsInfo = gson.fromJson(json, NewsInfo.class);
                    processNews(newsInfo.getValue());
                }else{
                    showEmptyView(articleList);
                }
            }

            @Override
            public void onFailure(String json) {
                if(articleList.isRefreshing()){
                    articleList.onRefreshComplete();
                }
                showEmptyView(articleList);
            }
        });
    }

    private void processNews(List<News> datas){
        if(pageIndex == 1){
            if(datas.size() == 0){
                showEmptyView(articleList);
            }else{
                dismissEmptyView();
            }
            newsList = datas;
            adapter = new NewsListAdapter(mActivity, newsList);
            articleList.setAdapter(adapter);
            if(datas.size() == Utils.ONCECOUNT){
                articleList.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }else{
            newsList.addAll(datas);
            adapter.notifyDataSetChanged();
        }

        if(datas.size() < Utils.ONCECOUNT){
            articleList.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    //提示对话框
    private void showDialog(final News news) {
        Typeface lantypeFace = Utils.getTypeface(mActivity);
        Typeface typeFace = Utils.getTypeface(mActivity);
        CustomPatient.Builder builder = new CustomPatient.Builder(mActivity);
        builder.setContent("是否取消文章收藏？", lantypeFace, typeFace);
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                        service.delNews(news);
                        newsList.remove(news);
                        adapter.notifyDataSetChanged();
                        Toast.makeText(mActivity, "操作成功", Toast.LENGTH_SHORT).show();
                    }
                });

        CustomPatient CustomPatient = builder.create();
        CustomPatient.show();
        Window window = CustomPatient.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.20); // 宽度设置为屏幕的0.20
        p.width = (int) (d.getWidth() * 0.70); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
    }
}
